package com.five.base.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.five.common.been.TokenEntity;
import com.five.common.util.BaseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.io.IOException;

/**
 * @ClassName TokenApplicationRunner
 * @Author Administrator
 * @Date 2018/12/31 16:03
 * @Version 1.0
 * @Description 项目启动执行获取token
 **/
@Component
@Slf4j
public class TokenApplicationRunner extends Thread{

    private static final int MAX=3;

    @Value("${appid}")
    private String appid;

    @Value("${appsecret}")
    private String appsecret;

    @Autowired
    private MailConfiguration mail;

    @Autowired
    private RedisTemplates redis;

    private int i = 0;

    @Scheduled(initialDelay = 1000, fixedDelay = 7000 * 1000)
    public void getAccessToken() throws IOException, MessagingException, InterruptedException {
        try {
            String URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
            String msg = BaseUtil.getBaseUtil().getToken("GET", URL);
            ObjectMapper mapper = new ObjectMapper();
            TokenEntity tokenEntity = mapper.readValue(msg, TokenEntity.class);
            redis.getRedisTemplate().opsForValue().set("token",tokenEntity.getAccess_token());
            log.info("token获取成功,并加入redis存储");
        }catch (Exception e){
            log.error("获取access_token异常,正在尝试第"+(i+1)+"次重新获取token");
            i++;
            if (i==MAX){
                log.error("超出重试次数限制,系统异常");
                i=0;
                if (mail.sendMail()){
                    log.info("邮件发送成功");
                }else {
                    log.error("邮件发送失败");
                }
            }else {
                Thread.sleep(1000);
                this.getAccessToken();
            }
        }
    }
}
